Contract = Ext.extend(Ext.Panel, {
    initComponent: function(tit) {
        this.layout ='border';
        this.frame = true;
        this.title = tit;
        this.contract_id = 0;
        this.provider_id = 0;
        this.consignee_id = 0;
        this.emptyPlan = [
            {"id":"1","type":"1","isplan":"1","contract_id":"0","m01":"0.00","m02":"0.00","m03":"0.00","m04":"0.00","m05":"0.00","m06":"0.00","m07":"0.00","m08":"0.00","m09":"0.00","m10":"0.00","m11":"0.00","m12":"0.00"},
            {"id":"2","type":"2","isplan":"1","contract_id":"0","m01":"0.00","m02":"0.00","m03":"0.00","m04":"0.00","m05":"0.00","m06":"0.00","m07":"0.00","m08":"0.00","m09":"0.00","m10":"0.00","m11":"0.00","m12":"0.00"}
        ];
        this.plan = [
            {"id":"1","type":"1","isplan":"1","contract_id":"0","m01":"0.00","m02":"0.00","m03":"0.00","m04":"0.00","m05":"0.00","m06":"0.00","m07":"0.00","m08":"0.00","m09":"0.00","m10":"0.00","m11":"0.00","m12":"0.00"},
            {"id":"2","type":"2","isplan":"1","contract_id":"0","m01":"0.00","m02":"0.00","m03":"0.00","m04":"0.00","m05":"0.00","m06":"0.00","m07":"0.00","m08":"0.00","m09":"0.00","m10":"0.00","m11":"0.00","m12":"0.00"}
        ];

        this.initPlanGrid();
        this.initContractForm();
        this.initAdditionalCast();

        this.items = [this.ContractForm, this.PlanGrid, this.AdditionalCastForm ];

        Contract.superclass.initComponent.call(this);
    },
    initContractForm: function() {
        this.curList = new Ext.form.ComboBox({
            width: 50, mode: 'local',
            triggerAction: 'all', ffValue: 0, submitValue : false, listClass: 'x-combo-list-small',
            hiddenName: 'contract_currency_id', store: curencyStore, valueField: 'currency_id', displayField: 's_name'
        });
        
        this.TCcurList = new Ext.form.ComboBox({
            width: 50, mode: 'local',
            triggerAction: 'all', ffValue: 0, submitValue : false, listClass: 'x-combo-list-small',
            hiddenName: 'TC_currency_id', store: curencyStore, valueField: 'currency_id', displayField: 's_name'
        });

        this.ACcurList = new Ext.form.ComboBox({
            width: 50, mode: 'local',
            triggerAction: 'all', ffValue: 0, submitValue : false, listClass: 'x-combo-list-small',
            hiddenName: 'AC_currency_id', store: curencyStore, valueField: 'currency_id', displayField: 's_name'
        });

        this.ContractForm = new Ext.form.FormPanel({
           region: 'north',
           height: 180,
           labelWidth: 150,
           border: false,
           //layout: 'border',
           items: [
                {xtype: 'textfield', fieldLabel: 'Наименование контракта', name: 'contract_name',  anchor: '100%'},
                {
                        layout: 'column',
                        items: [{
                                columnWidth:.45, layout: 'form',  //width: 300,
                                items: [{ xtype: 'numberfield', fieldLabel: 'Сумма контракта', name: 'contract_summ',  anchor: '100%' }]
                        },{
                                columnWidth:.01, //layout: 'form', //width: 100,
                                items: [ {xtype: 'label', text: '`', cls: 'fon'} ]
                        },{
                                columnWidth:.15,//layout: 'form', //width: 100,
                                items: [ this.curList ]
                        }]
                },
                { xtype: 'datefield', fieldLabel: 'Дата подписания', name: 'signing_date', allowBlank: false, minValue: '01.01.2006', maxValue: (new Date('2099 12 31')).format('d.m.Y')},
                { xtype: 'datefield', fieldLabel: 'Дата окончаня', name: 'expiration_date', allowBlank: false, minValue: '01.01.2006', maxValue: (new Date('2099 12 31')).format('d.m.Y')},
                { xtype: 'textarea', fieldLabel: 'Коментарий', name: 'comment',  anchor: '100%' },
                { xtype: 'hidden', name: 'contract_id' },
                { xtype: 'hidden', name: 'provider_id' },
                { xtype: 'hidden', name: 'consignee_id' },
                { xtype: 'hidden', name: 'plan' }
           ]
        });
    },
    initPlanGrid: function() {
        Ext.ux.grid.GroupSummary.Calculations['totalSumm'] = function(v, record, field){
            return ( parseFloat(record.data.m01) + parseFloat(record.data.m02) +parseFloat(record.data.m03) + parseFloat(record.data.m04) +parseFloat(record.data.m05) + parseFloat(record.data.m06) +
                parseFloat(record.data.m07) + parseFloat(record.data.m08) + parseFloat(record.data.m09) + parseFloat(record.data.m10) + parseFloat(record.data.m11) + parseFloat(record.data.m12) );
        };
        Ext.ux.grid.GroupSummary.Calculations['sub'] = function(v, record, field){
            var tt = (record.data.isplan == 1) ? record.data[field] : -record.data[field];
            return sprintf('%01.2f',  parseFloat(v) + parseFloat(tt) );
        }
        
        this.PlanStore = new Ext.data.JsonStore({
            autoLoad: true,
            root: 'data',
            fields:[
                { name: 'id', type: 'int' },
                { name: 'type', type: 'int' },
                { name: 'isplan', type: 'int' },
                { name: 'contract_id', type: 'int' },
                { name: 'm01', type: 'number' },
                { name: 'm02', type: 'number' },
                { name: 'm03', type: 'number' },
                { name: 'm04', type: 'number' },
                { name: 'm05', type: 'number' },
                { name: 'm06', type: 'number' },
                { name: 'm07', type: 'number' },
                { name: 'm08', type: 'number' },
                { name: 'm09', type: 'number' },
                { name: 'm10', type: 'number' },
                { name: 'm11', type: 'number' },
                { name: 'm12', type: 'number' },
                { name: 'total', type: 'number' }

            ],
            url: 'main?action=getEmptyPlan'
        }); 

        var NumFormat = function(value ) {  return sprintf('%01.2f', parseFloat( value ) ); };
        var Summ = function(value, metaData, record) {
            var val = parseFloat(parseFloat(record.data.m01)+parseFloat(record.data.m02)+parseFloat(record.data.m03)+parseFloat(record.data.m04)+
            parseFloat(record.data.m05)+parseFloat(record.data.m06)+parseFloat(record.data.m07)+parseFloat(record.data.m08)+
            parseFloat(record.data.m09)+parseFloat(record.data.m10)+parseFloat(record.data.m11)+parseFloat(record.data.m12));
            return sprintf('%01.2f', parseFloat( val ) );
        };

        this.PlanGrid =  new Ext.grid.EditorGridPanel({
            region: 'center',
            store: this.PlanStore,
            //height: 150,
            frame: false,
            border: true,
            loadMask: true,
            selModel: new Ext.grid.CellSelectionModel({}),
            colModel: new Ext.grid.ColumnModel({
                defaults: { width: 65, align: 'right' },
                columns: [
                    {header: 'Контракт', dataIndex: 'contract_id', hidden: true },
                    {header: '* * *', width: 70, css: 'color:#15428B; font:12px arial,tahoma,helvetica,sans-serif; font-weight:bold;', dataIndex: 'type', summaryRenderer: function(v, params, data){ return 'Баланс:'; }, renderer: function(value, metaData, record) { return (record.data.type == 1) ? 'Отработки' : 'Оплаты' ; } },
                    {header: 'Январь', dataIndex: 'm01', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Февраль', dataIndex: 'm02', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Март', dataIndex: 'm03', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Апрель', dataIndex: 'm04', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Май', dataIndex: 'm05', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Июнь', dataIndex: 'm06', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Июль', dataIndex: 'm07', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Август', dataIndex: 'm08', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Сентябрь', dataIndex: 'm09', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Октябрь', dataIndex: 'm10', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Ноябрь', dataIndex: 'm11', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Декабрь', dataIndex: 'm12', summaryType: 'sub', renderer: NumFormat, editor: new Ext.form.NumberField({ allowBlank: false, allowNegative: false, maxValue: 999999999999 }) },
                    {header: 'Итого', dataIndex: 'total', summaryType: 'totalSumm', renderer: Summ }
                ]
            }),
            title: 'План отработок и оплат',
            clicksToEdit: 1,
            bbar: [
                {xtype: 'tbbutton', text: 'Распределить равномерно', handler: function() {
                    var form = this.ContractForm.getForm();
                    var summ = form.items.items[1].getValue();
                    if(summ>0) { this.setPlanValues(summ/12); }
                    else error_mes('Ощибка','Вы не указали сумму контракта.');                    
                }, scope: this },'->',
                {xtype: 'tbbutton', text: 'Обнулить', handler: function() {
                    this.setPlanValues(0);
                }, scope: this }
            ]
        });
    },
    initAdditionalCast: function() {
          this.AdditionalCastForm = new Ext.form.FormPanel({
           region: 'south',
           style: 'margin-top: 10px;',
           bodyStyle: 'margin-top: 10px',
           height: 100,
           labelWidth: 200,
           border: true,
           title: 'Дополнительные параметры',
           items: [
                //{xtype: 'textfield', fieldLabel: 'Наименование контракта', name: 'contract_name',  anchor: '100%'},
                {
                        layout: 'column',
                        items: [{
                                columnWidth:.45, layout: 'form',  //width: 300,
                                items: [{ xtype: 'numberfield', fieldLabel: 'Трансферные расходы', name: 'additional_costs',  anchor: '100%' }]
                        },{
                                columnWidth:.01, //layout: 'form', //width: 100,
                                items: [ {xtype: 'label', text: '`', cls: 'fon'} ]
                        },{
                                columnWidth:.15,//layout: 'form', //width: 100,
                                items: [ this.TCcurList ]
                        }]
                },
                {
                        layout: 'column',
                        items: [{
                                columnWidth:.45, layout: 'form',  //width: 300,
                                items: [{ xtype: 'numberfield', fieldLabel: 'Дополнительные расходы', name: 'additional_costs',  anchor: '100%' }]
                        },{
                                columnWidth:.01, //layout: 'form', //width: 100,
                                items: [ {xtype: 'label', text: '`', cls: 'fon'} ]
                        },{
                                columnWidth:.15,//layout: 'form', //width: 100,
                                items: [ this.ACcurList ]
                        }]
                }
           ]
        });
    },
    setPlanValues: function(val) {
        for(var i=0; i<2; i++) {
            this.plan[i].m01 = val; this.plan[i].m02 = val; this.plan[i].m03 = val; this.plan[i].m04 = val; this.plan[i].m05 = val; this.plan[i].m06 = val;
            this.plan[i].m07 = val; this.plan[i].m08 = val; this.plan[i].m09 = val; this.plan[i].m10 = val; this.plan[i].m11 = val; this.plan[i].m12 = val;
        }
        this.PlanStore.data.items[0].data = this.plan[0];
        this.PlanStore.data.items[1].data = this.plan[1];
        this.PlanGrid.getView().refresh();
    },
    getFormData: function() {
        var form = this.ContractForm.getForm();
        form.items.items[6].setValue(this.contract_id);
        form.items.items[7].setValue(this.provider_id);
        form.items.items[8].setValue(this.consignee_id);
        this.PlanStore.commitChanges();
        this.plan[0] = this.PlanStore.data.items[0].data;
        this.plan[1] = this.PlanStore.data.items[1].data;
        form.items.items[9].setValue( this.Serialize(this.plan) );
        return form.getValues();
    },
    getPlanData: function() {
        return this.plan;
    },
    PlanResset: function() {
        this.plan = this.emptyPlan;
        this.PlanStore.data.items[0].data = this.plan[0];
        this.PlanStore.data.items[1].data = this.plan[1];
        this.PlanGrid.getView().refresh();
    },
    setContactData: function(data) {
        this.ContractForm.getForm().reset();
        this.ContractForm.getForm().setValues(data);

        this.contract_id = data.contract_id;
        this.provider_id = data.provider_id;
        this.consignee_id = data.consignee_id;
    },
    getContractData: function() {
        Ext.Ajax.request({
            url: 'main?action=getContractDetail',
            params: { contract_id: this.contract_id },
            scope: this,
            callback: function(options, success, response) {
                var ansv = Ext.decode(response.responseText);
                if(ansv.sucsess === true ) {
                    if(ansv.data[0]) {
                        this.setContactData(ansv.data[0]);

                        if(ansv.plan[0]) {
                            this.plan = ansv.plan;                            
                        } else this.plan = this.emptyPlan;
                        this.PlanStore.data.items[0].data = this.plan[0];
                        this.PlanStore.data.items[1].data = this.plan[1];
                        this.PlanGrid.getView().refresh();
                    }
                } else { error_mes('Ошибка',  ansv.error); }
            }
        });
    },
    Serialize: function( mixed_value ) {

        // http://kevin.vanzonneveld.net
        // +   original by: Arpad Ray (mailto:arpad@php.net)
        // +   improved by: Dino
        // +   bugfixed by: Andrej Pavlovic
        // +   bugfixed by: Garagoth
        // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
        // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
        // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
        // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
        // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
        // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'

        var _getType = function( inp ) {
            var type = typeof inp, match;
            var key;
            if (type == 'object' && !inp) {
                return 'null';
            }
            if (type == "object") {
                if (!inp.constructor) {
                    return 'object';
                }
                var cons = inp.constructor.toString();
                if (match = cons.match(/(\w+)\(/)) {
                    cons = match[1].toLowerCase();
                }
                var types = ["boolean", "number", "string", "array"];
                for (key in types) {
                    if (cons == types[key]) {
                        type = types[key];
                        break;
                    }
                }
            }
            return type;
        };
        var type = _getType(mixed_value);
        var val, ktype = '';

        switch (type) {
            case "function":
                val = "";
                break;
            case "undefined":
                val = "N";
                break;
            case "boolean":
                val = "b:" + (mixed_value ? "1" : "0");
                break;
            case "number":
                val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
                break;
            case "string":
                val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
                break;
            case "array":
            case "object":
                val = "a";
                /*
                if (type == "object") {
                    var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                    if (objname == undefined) {
                        return;
                    }
                    objname[1] = serialize(objname[1]);
                    val = "O" + objname[1].substring(1, objname[1].length - 1);
                }
                */
                var count = 0;
                var vals = "";
                var okey;
                var key;
                for (key in mixed_value) {
                    ktype = _getType(mixed_value[key]);
                    if (ktype == "function") {
                        continue;
                    }

                    okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                    vals += this.Serialize(okey) +
                            this.Serialize(mixed_value[key]);
                    count++;
                }
                val += ":" + count + ":{" + vals + "}";
                break;
        }
        if (type != "object" && type != "array") val += ";";
        return val;
    }
});


